import { login } from '@/api/login'
import { storage } from '@/util/storage'
import { removeToken, setToken } from '@/util/token'

const state = {
  user: {},
  routeList: [],
}

const getters = {
  user: (state) => state.user,
}

const mutations = {
  setUser: (state, user) => {
    state.user = user
  },
}

const actions = {
  setUser: ({ commit }, user) => {
    commit('setUser', user)
    storage.setItem('user', user)
  },
  reset: ({ commit, state }) => {
    state.user = {}
    removeToken()
  },

  login: ({ dispatch }, loginForm) => {
    return new Promise((resolve, reject) => {
      login(loginForm)
        .then((res) => {
          // 先清空
          storage.clear()
          const { token, user } = res.data
          setToken(token)
          dispatch('setUser', user)
          resolve(res.msg)
        })
        .catch((err) => {
          console.log(err)
          reject(err)
        })
    })
  },
  logout: ({ dispatch }) => {
    dispatch('reset')
    storage.clear()
  },
  getUserInfo: async ({ dispatch }) => {
    const user = await storage.getItem('user')
    dispatch('setUser', user)
  },
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
}
